package com.hnjfzn.auth.factory;

import com.hnjfzn.auth.service.SysPasswordService;
import com.hnjfzn.auth.service.SysRecordLogService;
import com.hnjfzn.common.core.constant.CacheConstants;
import com.hnjfzn.common.core.constant.Constants;
import com.hnjfzn.common.core.constant.SecurityConstants;
import com.hnjfzn.common.core.domain.R;
import com.hnjfzn.common.core.enums.UserStatus;
import com.hnjfzn.common.core.exception.ServiceException;
import com.hnjfzn.common.core.text.Convert;
import com.hnjfzn.common.core.utils.DateUtils;
import com.hnjfzn.common.core.utils.ip.IpUtils;
import com.hnjfzn.common.redis.service.RedisService;
import com.hnjfzn.system.api.RemoteUserService;
import com.hnjfzn.system.api.domain.SysUser;
import com.hnjfzn.system.api.model.LoginUser;

/**
 * 登录校验方法
 */
public abstract class AbsSysLogin {
    protected RemoteUserService remoteUserService;
    protected SysPasswordService passwordService;
    protected SysRecordLogService recordLogService;
    protected RedisService redisService;

    /**
     * 构造
     *
     * @param remoteUserService 远程用户服务
     * @param passwordService 密码服务
     * @param recordLogService 日志服务
     * @param redisService 缓存服务
     */
    public AbsSysLogin(RemoteUserService remoteUserService, SysPasswordService passwordService, SysRecordLogService recordLogService, RedisService redisService) {
        this.remoteUserService = remoteUserService;
        this.passwordService = passwordService;
        this.recordLogService = recordLogService;
        this.redisService = redisService;
    }

    /**
     * 前期验证
     * @param args 参数
     */
    protected abstract void validAfter(String... args);

    /**
     * 后期验证
     *
     * @param user 用户
     * @param args 参数
     */
    protected abstract void validBefore(SysUser user, String... args);

    /**
     * 登录
     */
    public LoginUser login(String... args) {
        String v1 = args[0];
        // 校验
        validAfter(args);

        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr()))
        {
            recordLogService.recordLogininfor(v1, Constants.LOGIN_FAIL, "很遗憾，访问IP已被列入系统黑名单");
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(v1, SecurityConstants.INNER);
        // 认证异常
        if (R.FAIL == userResult.getCode()){
            throw new ServiceException(userResult.getMsg());
        }
        // 登录用户
        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "对不起，您的账号已被删除");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_FAIL, "用户已停用，请联系管理员");
            throw new ServiceException("对不起，您的账号：" + user.getUserName() + " 已停用");
        }
        // 后期验证
        validBefore(user, args);
        // 信息记录
        recordLogService.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS, "登录成功");
        recordLoginInfo(user.getUserId());
        return userInfo;
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId)
    {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        // 更新用户登录IP
        sysUser.setLoginIp(IpUtils.getIpAddr());
        // 更新用户登录时间
        sysUser.setLoginDate(DateUtils.getNowDate());
        remoteUserService.recordUserLogin(sysUser, SecurityConstants.INNER);
    }
}
